package com.smallyang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smallyang.constants.RedisConstants;
import com.smallyang.constants.SystemConstants;
import com.smallyang.domain.ResponseResult;
import com.smallyang.domain.dto.AddArticleDto;
import com.smallyang.domain.dto.ArticleDto;
import com.smallyang.domain.entity.Article;
import com.smallyang.domain.entity.ArticleTag;
import com.smallyang.domain.entity.Category;
import com.smallyang.domain.vo.*;
import com.smallyang.mapper.ArticleMapper;
import com.smallyang.service.ArticleService;
import com.smallyang.service.ArticleTagService;
import com.smallyang.service.CategoryService;
import com.smallyang.utils.BeanCopyUtils;
import com.smallyang.utils.DataUtil;
import com.smallyang.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 杨森
 * @description:
 * @date 2023年05月12日 8:50
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleTagService articleTagService;

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章 封装成ResponseResult返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //必须是未被删除的文章
        queryWrapper.eq(Article::getDelFlag, SystemConstants.NOT_DEL_FLAG);

        //按照浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);

        //最多只能查询十条文章
        Page<Article> page = new Page<>(1, 10);
        page(page, queryWrapper);

        //查询数据库所有的字段封装为articles
        List<Article> articles = page.getRecords();
        //前端展示需要的字段，需要用vo,bean拷贝
//        List<HotArticleVo> articleVos = new ArrayList<>();
//        for (Article article : articles) {
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);
//        }
        List<HotArticleVo> articleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);

        return ResponseResult.okResult(articleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> lambda = new LambdaQueryWrapper<>();
        //如果有categoryId 就要求查询时要和传入的相同
        lambda.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);
        //状态是是正式发布的
        lambda.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        lambda.eq(Article::getDelFlag, SystemConstants.NOT_DEL_FLAG);
        //置顶的文章显示在最前面 对isTop进行降序
        lambda.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, lambda);
        //查询categoryName
        List<Article> articles = page.getRecords();
        //articleId去查询articleName进行配置
        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
                .collect(Collectors.toList());

        //封装查询结果
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        //从redis中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue(RedisConstants.ARTICLE_VIEWCOUNT_KEY, id.toString());
        article.setViewCount(viewCount.longValue());

        //转换成VO
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }
        //封装相应返回
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应id的浏览量
        redisCache.incrementCacheMapValue(RedisConstants.ARTICLE_VIEWCOUNT_KEY, id.toString(), 1);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional//事务注解
    public ResponseResult add(AddArticleDto articleDto) {
        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);


        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public PageVo selectArticlePage(Article article, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();

        queryWrapper.like(StringUtils.hasText(article.getTitle()), Article::getTitle, article.getTitle());
        queryWrapper.like(StringUtils.hasText(article.getSummary()), Article::getSummary, article.getSummary());

        Page<Article> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        page(page, queryWrapper);

        //转换成VO
        List<ArticleListVo> articleListVo = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);

        PageVo pageVo = new PageVo();
        pageVo.setTotal(page.getTotal());
        pageVo.setRows(articleListVo);
        return pageVo;
    }

    @Override
    public ArticleVo getInfo(Long id) {
        Article article = getById(id);
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId, id);
        List<ArticleTag> articleTags = articleTagService.list(queryWrapper);
        List<Long> tags = articleTags.stream().map(articleTag -> articleTag.getTagId()).collect(Collectors.toList());

        ArticleVo articleVo = BeanCopyUtils.copyBean(article, ArticleVo.class);
        articleVo.setTags(tags);
        return articleVo;
    }

    @Override
    public void updateArticle(ArticleDto updateArticle) {
        Article article = BeanCopyUtils.copyBean(updateArticle, Article.class);
        //更新博客信息
        updateById(article);

        //删除原有的 标签和博客的关联
        LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleTagLambdaQueryWrapper.eq(ArticleTag::getArticleId, article.getId());
        articleTagService.remove(articleTagLambdaQueryWrapper);

        //添加新的博客和标签的关联信息
        List<ArticleTag> tags = updateArticle.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        articleTagService.saveBatch(tags);
    }

    @Override
    public ResponseResult deleteArticle(List<Long> id) {
        for (Long tagId : id) {
            removeById(tagId);
        }
        return ResponseResult.okResult();
    }

    //文章条形图
    @Override
    public BarVo barVoList() {
        BarVo barVo = new BarVo();
        List<String> names = new ArrayList<>();
        List<DataVo> values = new ArrayList<>();

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //必须是未被删除的文章
        queryWrapper.eq(Article::getDelFlag, SystemConstants.NOT_DEL_FLAG);

        //先查出数据
        List<Article> articles = list(queryWrapper);

        for (Article article : articles) {
            names.add(article.getTitle());
//            System.out.println(article.getViewCount());
            DataVo dataVol = new DataVo();
            dataVol.setValue(article.getViewCount());
            dataVol.setItemStyle(DataUtil.createItemStyle(Integer.parseInt(article.getViewCount().toString())));
            values.add(dataVol);
        }

        barVo.setNames(names);
        barVo.setValues(values);
        //转换VO
        return barVo;
    }

    @Override
    public List<PieVo> pieVoList() {
        List<PieVo> pieVOList = new ArrayList<>();

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //必须是未被删除的文章
        queryWrapper.eq(Article::getDelFlag, SystemConstants.NOT_DEL_FLAG);

        //先查出数据
        List<Article> articles = list(queryWrapper);
        for (Article article : articles) {
            PieVo pieVO = new PieVo();
            pieVO.setValue(article.getViewCount());
            pieVO.setName(article.getTitle());
            pieVO.setItemStyle(DataUtil.createItemStyle(Integer.parseInt(article.getViewCount().toString())));
            pieVOList.add(pieVO);
        }
        return pieVOList;
    }

}
